<template>
   <div class="upload-container">
     <div class="upload-content">
       <h3 class="header">上传文件</h3>
       <el-upload
           class="upload-demo"
           drag
           action="#"
           show-file-list
           :file-list="fileList"
           :on-remove="handleRemove"
           list-type="text"
           :before-upload="beforeUpLoad"
           multiple>
         <i class="el-icon-upload"></i>
         <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
         <template #tip>
           <div class="el-upload__tip">
             <el-alert
                 title="支持多文件上传"
                 type="warning"
                 :closable="false"
                 show-icon>
             </el-alert>
           </div>
         </template>
       </el-upload>
       <div class="upload-btn-container">
         <el-button
             class="upload-btn"
             type="primary"
             round
             icon="el-icon-upload"
             @click="uploadFile"
         >
           上传
         </el-button>
       </div>
     </div>
   </div>
</template>
<script lang="ts">
import {defineComponent, ref} from 'vue'
import {errorMessage, successMessage} from "/@/utils/message";
import {dataType, upload} from "/@/api";
export default defineComponent({
  name:'',
  setup(){
    // 定义file对象类型
    interface fileType{
      name:string|null,
      url:string|ArrayBuffer,
      uid:number|string
    }
    // 初始化文件列表为空数组
    const fileList=ref<Array<fileType>>([])
    // 解码base64文件为file类型
    const convert=(urlData:any,fileName:string):File|Blob=>{
      let arr = urlData.split(',');
      let mime = arr[0].match(/:(.*?);/)[1];
      let bytes = atob(arr[1]); // 解码base64
      let n = bytes.length
      let ia = new Uint8Array(n);
      while (n--) {
        ia[n] = bytes.charCodeAt(n);
      }
      return new File([ia], fileName, { type: mime });
      // return new Blob([ia],{type:mime})
    }
    // 上传文件前的处理函数
    const beforeUpLoad=(file:fileType):boolean=>{
      // 创建FileReader实例，用于读取文件
      let reader=new FileReader()
      // 将文件以base64编码读入
      //@ts-ignore
      reader.readAsDataURL(file)
      // 当文件读入完成后，添加base编码文件到fileList中
      reader.onload=function(){
        fileList.value.push({
          name:file.name,
          url:reader.result,
          uid:file.uid
        })
      }
      return false
    }
    // 从文件列表中删除指定文件的处理函数
    const handleRemove=(file)=>{
      fileList.value=fileList.value.filter(item=>item.uid!==file.uid)
    }
    // 上传文件的处理函数
    const uploadFile=async ()=>{
      // 当文件列表为空的时候，提示用户并终止上传
      if(fileList.value.length===0){
        errorMessage('请上传文件！！！')
        return
      }
      // 创建FormData对象用于上传文件
       let formData=new FormData()
      // 创建fileArray用于接收文件列表
       fileList.value?.forEach(item=>{
         // 转换文件编码后存入fileArray
         formData.append('multipartFiles', convert(item.url,item.name))
       })
       // 创建表单字段
       try{
         const res:any=await upload(formData)
         if(res.code==='200'){
           successMessage('上传文件成功！！')
         }else{
           errorMessage('网络错误！')
         }
       }catch (e) {
         errorMessage('网络错误！')
       }

    }
    return{
      handleRemove,
      beforeUpLoad,
      uploadFile,
      fileList
    }

  }
})
</script>

<style lang='scss' scoped>

.upload-container{
  width:100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  .upload-content{
    width:40%;
    padding:30px 0;
    .header{
      text-align: center;
    }
    .upload-btn-container{
      width:100%;
      text-align: center;
      margin:20px auto;
    }
    .upload-btn{
      width:40%;
    }
  }
}
</style>
